<template>
  <div class="login-container">
    <el-form :model="form" :rules="rules" ref="loginForm" label-width="100px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="form.username"></el-input>
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input type="password" v-model="form.password" show-password></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm">登录</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { reactive, ref } from 'vue'
import { login } from '@/apis/login'
import { setCookie } from '@/utils/cookie'
import { useRouter } from 'vue-router'
// router === this.$router
const router = useRouter()
const form = reactive({
  username: 'heima-tool',
  password: 'admin123'
})

const rules = reactive({
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
})

const loginForm = ref(null)

const submitForm = () => {
  loginForm.value.validate(async(valid) => {
    if (valid) {
      // 1. 提交登录信息 -> 发请求
      const res = await login(form)
      console.log(res)
      // 2. 存储token -> cookie
      setCookie(res.data.token)
      // 3. 跳转到首页 -> 大屏
      router.push('/big-screen')
    } 
  })
}
</script>

<style scoped>
.login-container {
  width: 400px;
  margin: 100px auto;
  padding: 20px;
  border: 1px solid #ccc;
  border-radius: 5px;
}
</style>